package com.kele.web.vertx.provider.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.tracing.TracingPolicy;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.servicediscovery.ServiceDiscovery;
import io.vertx.servicediscovery.types.HttpEndpoint;
import io.vertx.sqlclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xujiale 2021/2/28 22:10
 */

public class RestVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestVerticle.class);

    protected MySQLPool client;

    protected ServiceDiscovery discovery;

    private void initServiceDiscovery() {
        discovery = ServiceDiscovery.create(vertx);
    }

    private void initMysqlPool() {
        MySQLConnectOptions connectOptions = new MySQLConnectOptions()
                .setTracingPolicy(TracingPolicy.ALWAYS)
                .setCachePreparedStatements(true)
                .setCharset("utf8mb4")
                .setCollation("utf8_general_ci")
                .setPort(3306)
                .setHost("localhost")
                .setDatabase("dev")
                .setUser("xukele")
                .setPassword("kele1234");
        PoolOptions poolOptions = new PoolOptions()
                .setMaxSize(10);
        client = MySQLPool.pool(vertx, connectOptions, poolOptions);
    }


    @Override
    public void start() throws Exception {
        initMysqlPool();
        initServiceDiscovery();
        Router router = Router.router(vertx);
        HttpServerOptions httpServerOptions = new HttpServerOptions().setLogActivity(true);
        vertx.createHttpServer(httpServerOptions)
                .requestHandler(router)
                .listen(80, "kele.com", res -> {
                    if (res.succeeded()) {
                        LOGGER.info("http 服务启动:{}", res.result());
                    } else {
                        LOGGER.error("HTTP_SERVER START FAILED:", res.cause());
                    }
                });

        router.get("/kele").respond(func -> Future.succeededFuture(new JsonObject().put("tom", "oh yes")));

        router.get("/db").handler(rctx -> {
            client.getConnection()
                    .compose(connection -> queryUser(connection, 2))
                    .onSuccess(rowset -> handlerRowSet(rowset, rctx));
        });


        discovery.publish(HttpEndpoint.createRecord("db", "kele.com", 80, "/db"), ar -> {
            if (ar.succeeded()) {
                LOGGER.info("接口发布成功:{}", "/db");
            }else {
                LOGGER.warn("接口发布失败");
            }
        });

    }

    private void handlerRowSet(RowSet<Row> rowset, RoutingContext rctx) {
        JsonArray jsonArray = new JsonArray();
        for (Row row : rowset) {
            jsonArray.add(row.toJson());
        }
        rctx.json(jsonArray);
    }

    private Future<RowSet<Row>> queryUser(SqlConnection connection, int userId) {
        Promise<RowSet<Row>> promise = Promise.promise();
        connection.preparedQuery("select * from ls_shop_user where user_id=?")
                .execute(Tuple.of(userId), ar -> {
                    if (ar.succeeded()) {
                        promise.complete(ar.result());
                    } else {
                        promise.fail(ar.cause());
                    }
                });
        return promise.future();
    }


    @Override
    public void stop(Promise<Void> stopPromise) throws Exception {
        client.close();
    }
}
